<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <h1>Page Cookie</h1>
        <button onclick="setCookie()">设置普通cookie</button>
        <button onclick="setTime()">设置100秒过期的cookie</button>
        <button onclick="delCookie('userId')">删除cookie</button>
    </div>
    <script>
        //直接设置cookie
        function setCookie(){
            var dataCookie = '110';
            document.cookie = 'token' + "=" + dataCookie;
        }
        
        //获取指定名称的cookie值
        function getCookie(name) { 
            var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));// (^| )name=([^;]*)(;|$),match[0]为与整个正则表达式匹配的字符串，match[i]为正则表达式捕获数组相匹配的数组；
            if (arr != null) {
                console.log(arr, '正则表达式捕获数组相匹配的数组');
                return unescape(arr[2]);
            }
            return null;
        }
        var cookieData = getCookie('token');
        console.log(cookieData, '获取指定名称的cookie值');

        //存储cookie值并且设置cookie过期时间
        function setTime() {
            var date = new Date();
            console.log('date',date);
            var second = 100;//设置十秒过期
            date.setTime(date.getTime()+second*1000);
            document.cookie="userId=828;  expires="+date.toGMTString();
            console.log(document.cookie, '存储cookie值并且设置cookie过期时间');
        }
        // setTime();

        //删除cookie
        function delCookie(cookieName1) {
            var date2 = new Date();
            date2.setTime(date2.getTime() - 10001);//把时间设置为过去的时间，会自动删除
            document.cookie = cookieName1 + "=v; expires=" + date2.toGMTString();
            console.log(document.cookie, '删除cookie');
        }
        // delCookie('userId');
    </script>
</body>

</html>